<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>水路供应商管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--    <link rel="stylesheet" href="../web/resource/css/allcss/allCss.css" type="text/css">-->
    <style>

    </style>
</head>
<body>
<div class="query-container">
    <div class="form-row">
        <!-- 供应商名称 -->
        <div class="form-item">
            <label class="form-label">供应商：</label>
            <input type="text"
                   class="form-input"
                   placeholder="请输入供应商名称">
        </div>

        <!-- 状态选择 -->
        <div class="form-item">
            <label class="form-label">状态：</label>
            <select class="form-input form-select">
                <option value="">全部</option>
                <option value="0">待审核</option>
                <option value="1">合作中</option>
                <option value="2">终止合作</option>
                <option value="3">已取消</option>
            </select>
        </div>
    </div>
    <!-- 操作按钮 -->
    <div class="action-buttons">
        <button class="btn btn-reset">重置</button>
        <button class="btn btn-query">查询</button>
        <button class="btn btn-add">新增</button>
    </div>
</div>
<div class="table-container">
    <table class="data-table">
        <thead class="data-table-thead">
        <tr>
            <th>序号</th>
            <th>供应商全称</th>
            <th>供应商简称</th>
            <th>详情地址</th>
            <th>添加时间</th>
            <th>状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <!-- 分页 -->
</div>
<div class="pagination">
    <span>共0条</span>
    <select class="data-table-page" >
        <option class="" value="10" selected>10条/页</option>
        <option class="" value="20">20条/页</option>
        <option class="" value="50">50条/页</option>
    </select>
    <div class="page-num">
        <button class="pre-button">＜</button>
        <span>1</span>
        <button class="next-button">＞</button>
    </div>
</div>
<div class="modal-mask" id="modal-mask-add">
    <div class="modal-content">
        <h3 class="modal-title">
            新增水路供应商
            <button class="modal-close-btn">×</button>
        </h3>
        <form class="modal-form" id="modal-form-add">
            <div class="form-item">
                <label>供应商全称：</label>
                <input type="text" id="add-name" placeholder="请输入供应商全称" required>
            </div>
            <div class="form-item">
                <label>供应商简称：</label>
                <input type="text" id="add-shortName" placeholder="请输入供应商简称" required>
            </div>
            <div class="form-item">
                <label>详情地址：</label>
                <input type="text" id="add-address" placeholder="请输入详情地址" required>
            </div>
            <div class="form-item">
                <label>联系电话：</label>
                <input type="text" id="add-phone" placeholder="请输入联系电话" required>
            </div>
            <div class="form-item">
                <label>邮箱：</label>
                <input type="email" id="add-email" placeholder="请输入邮箱">
            </div>
            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">新增</button>
            </div>
        </form>
    </div>
</div>
<div class="modal-mask" id="modal-mask-update">
    <div class="modal-content">
        <h3 class="modal-title">
            修改供应商
            <button class="modal-close-btn">×</button>
        </h3>

        <form class="modal-form" id="modal-form-update">
            <div class="form-item">
                <label>供应商全称：</label>
                <input type="text" id="update-name" required>
            </div>
            <div class="form-item">
                <label>供应商简称：</label>
                <input type="text" id="update-shortName" required>
            </div>
            <div class="form-item">
                <label>详情地址：</label>
                <input type="text" id="update-address" required>
            </div>
            <div class="form-item">
                <label>联系电话：</label>
                <input type="text" id="update-phone" required>
            </div>
            <div class="form-item">
                <label>邮箱：</label>
                <input type="email" id="update-email">
            </div>
            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">保存</button>
            </div>
        </form>
    </div>
</div>
<div class="modal-mask" id="modal-mask-detail">
    <div class="modal-content">
        <h3 class="modal-title">
            供应商详情
            <button class="modal-close-btn">×</button>
        </h3>
        <div class="modal-body">
            <!-- 基础信息 -->
            <div class="detail-section">
                <h4 class="detail-subtitle">基础信息</h4>
                <div class="detail-row">
                    <span class="detail-label">供应商全称：</span>
                    <span id="detail-name" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">供应商简称：</span>
                    <span id="detail-shortName" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">联系电话：</span>
                    <span id="detail-phone" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">邮箱：</span>
                    <span id="detail-mailbox" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">详情地址：</span>
                    <span id="detail-address" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">状态：</span>
                    <span id="detail-status" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">创建时间：</span>
                    <span id="detail-createTime" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">更新时间：</span>
                    <span id="detail-updateTime" class="detail-value"></span>
                </div>
            </div>

            <!-- 操作记录 -->
            <div class="detail-section">
                <h4 class="detail-subtitle">操作记录</h4>
                <div id="detail-operationLogs" class="detail-logs">
                    暂无数据
                </div>
            </div>
        </div>
        <div class="modal-buttons">
            <button type="button" class="btn-close">关闭</button>
        </div>
    </div>
</div>
<script>
    const nextButton = document.querySelector('.next-button')
    const preButton = document.querySelector('.pre-button')
    //渲染
    function renderTable(data) {
        document.querySelector('.pagination span:first-child')
            .textContent = `共${data.data.total}条`;
        const tbody = document.querySelector('.data-table tbody');

        // 更新页码显示
        document.querySelector('.page-num span').textContent = data.data.current;

        if (data.data.current >= data.data.pages){
            nextButton.disabled = true;
            nextButton.style.opacity = "0.5";
        }else {
            nextButton.disabled = false;
            nextButton.style.opacity = "1";
        }

        if (data.data.current <= 1){
            preButton.disabled = true;
            preButton.style.opacity = "0.5";
        }else {
            preButton.disabled = false;
            preButton.style.opacity = "1";
        }

        tbody.innerHTML = ''; // 清空旧数据
        data.data.records.
        slice( // 根据分页参数切割数据
            (data.data.current - 1)
            * data.data.size,
            data.data.current * data.data.size
        ).forEach((item, index) => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${(data.data.current - 1) * data.data.size + index + 1}</td>
                <td>${item.name || ''}</td>
                <td>${item.shortName || ''}</td>
                <td>${item.address || ''}</td>
                <td>${formatDateTime(item.createTime)}</td>
                <td>${getStatusText(item.status)}</td>
                <td>
                     <button class="table-detail-btn">详情</button>
                    <button class="table-disable-btn">禁用</button>
                    <button class="table-edit-btn">修改</button>
                </td>
    `;

            // 绑定操作按钮事件
            const detailBtn = tr.querySelector('.table-detail-btn');
            const disableBtn = tr.querySelector('.table-disable-btn');
            const editBtn = tr.querySelector('.table-edit-btn');

            let state =0;
            if ( item.status ===0){
                state ='启用合作'
            }else if( item.status ===1){
                state ='终止合作'
            }
            // 禁用/启用切换
            disableBtn.addEventListener('click', () => disableRole(item.id, item.status));
            disableBtn.textContent = state;

            // 修改功能
            editBtn.addEventListener('click', () => updateRole(item));

            detailBtn.addEventListener('click', () => showHighDetail(item));
            tbody.appendChild(tr);
        });
    }
    document.querySelector('.btn-query').addEventListener('click',function (){
        fetchData('query');
    })
    document.querySelector('.pre-button').addEventListener('click',function (){
        fetchData('pre');
    })
    document.querySelector('.next-button').addEventListener('click',function (){
        fetchData('next');
    })
    // 统一请求方法
    async function fetchData(type) {

        let { page, pageSize } = getPaginationParams();

        if (type === 'pre') {
            page = Math.max(1, page - 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }else if (type === 'next'){
            page = Math.max(1, page + 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }

        const queryParams = {
            name: document.querySelector('input[placeholder="请输入供应商名称"]').value,
            status: document.querySelector('.form-select').value,
            page: page,
            rows: pageSize
        };

        try {
            const response = await fetch('http://localhost:8080/sys/waterway/pageList', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(queryParams)
            });

            const data = await response.json();
            if (data.status === 0) {
                renderTable(data);
                // console.log(data.data)
            }else  if (data.status === -1) {
                console.error('请求失败:', error);
            }
        } catch (error) {
            console.error('请求失败:', error);
            renderTable({ data: { records: [], total: 0, current: 1, pages: 0 } });
        }
    }
    //重置按钮
    document.querySelector('.btn-reset').addEventListener('click',()=>{
        document.querySelectorAll('.form-input').forEach(input => {
            if (input.type === 'text') input.value = '';
            if (input.tagName === 'SELECT') input.value = '';
        });

    })
    //新增按钮相关
    // 显示弹窗
    document.querySelector('.btn-add').addEventListener('click', () => {
        document.querySelector('#modal-mask-add').style.display = 'flex'
    })
    // 关闭弹窗
    document.querySelectorAll('.modal-close-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });

    document.querySelectorAll('.btn-close').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });
    // 表单提交处理
    document.querySelector('#modal-form-add').addEventListener('submit', async (e) => {
        e.preventDefault();

        const formData = {
            name: document.getElementById('add-name').value,
            shortName: document.getElementById('add-shortName').value,
            address: document.getElementById('add-address').value,
            phone: document.getElementById('add-phone').value,
            email: document.getElementById('add-email').value
        };

        try {
            const response = await fetch('http://localhost:8080/sys/waterway/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            const data = await response.json();
            if (data.status === 0) {
                alert('添加成功');
                document.getElementById('modal-mask-add').style.display = 'none';
                document.getElementById('modal-form-add').reset();
                fetchData('query');
            } else {
                alert('添加失败：' + (data.message || '未知错误'));
            }
        } catch (error) {
            console.error('提交失败:', error);
            alert('提交失败：' + error.message);
        }
    });
    //表格函数
    async function showHighDetail(item) {
        const modal = document.getElementById('modal-mask-detail');
        try {
            // 清空旧数据
            document.getElementById('detail-operationLogs').innerHTML = "加载中...";

            const res = await fetch(`http://localhost:8080/sys/waterway/detail/${item.id}`);
            const response = await res.json();

            if (response.status === 0) {
                const data = response.data;

                // 更新基础信息
                document.getElementById('detail-name').textContent = data.name || '--';
                document.getElementById('detail-shortName').textContent = data.shortName || '--';
                document.getElementById('detail-phone').textContent = data.phone || '--';
                document.getElementById('detail-mailbox').textContent = data.email || '未填写';
                document.getElementById('detail-address').textContent = data.address || '未填写';
                document.getElementById('detail-status').textContent = getStatusText(data.status);
                document.getElementById('detail-createTime').textContent = formatDateTime(data.createTime);
                document.getElementById('detail-updateTime').textContent = data.updateTime ? formatDateTime(data.updateTime) : '--';

                // 更新操作记录
                const logsContainer = document.getElementById('detail-operationLogs');
                if (data.operateRecordList?.length > 0) {
                    logsContainer.innerHTML = data.operateRecordList.map(log => `
                    <div class="log-item">
                        <span class="log-time">${formatDateTime(log.createTime)}</span>
                        <span class="log-type">${log.operateType}</span>
                        ${log.remark ? `<span class="log-remark">（${log.remark}）</span>` : ''}
                    </div>
                `).join('');
                } else {
                    logsContainer.innerHTML = '<div class="no-data">暂无操作记录</div>';
                }

                modal.style.display = 'flex';
            } else {
                alert('获取详情失败：' + (response.message || '未知错误'));
            }
        } catch (err) {
            console.error('详情加载失败:', err);
            document.getElementById('detail-operationLogs').innerHTML =
                '<div class="error-msg">记录加载失败</div>';
            alert(`加载失败: ${err.message}`);
        }
    }
    async function disableRole(id, currentStatus) {

        let newStatus ='';
        let newre ='';
        if(currentStatus ===0){
            newStatus = 1;
            newre='启用合作';
        }else if(currentStatus ===1){
            newStatus = 0;
            newre='停止合作';
        }
        try {
            const res = await fetch(`http://localhost:8080/sys/waterway/disable`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ id, status: newStatus })
            });
            const data = await res.json();

            if(data.status === 0) {
                alert(`已${newre}`);
                fetchData('query');
            }else {
                alert(`${newre}`);
            }
        } catch(err) {
            console.error('状态修改失败:', err);
        }
    }
    // 修改功能弹窗
    let currentEditHandler = null;
    // 修改功能（需要实现编辑弹窗）
    // function updateRole(item) {
    //     // 打开编辑弹窗
    //     // table-edit-btn
    //     const form = document.getElementById('modal-form-update');
    //     const modal = document.querySelector('#modal-mask-update'); // 需要创建编辑弹窗结构
    //     // 关闭旧监听器
    //     if (currentEditHandler) {
    //         form.removeEventListener('submit', currentEditHandler);
    //     }
    //     // 填充表单数据
    //     let typeName= document.querySelector('#edit-roleNm').value = item.typeName;
    //     let explaind=document.querySelector('#edit-explaind').value = item.explaind;
    //
    //
    //
    //     // 绑定提交事件
    //     // 定义新处理器
    //     currentEditHandler = async (e) => {
    //         e.preventDefault();
    //         const formData = {
    //             id: item.id,
    //             typeName: document.querySelector('#edit-roleNm').value,
    //             explaind: document.querySelector('#edit-explaind').value,
    //         };
    //
    //         try {
    //             const res = await fetch('http://localhost:8080/sys/highway/update', {
    //                 method: 'POST',
    //                 headers: {'Content-Type': 'application/json'},
    //                 body: JSON.stringify(formData)
    //             });
    //
    //             const data = await res.json();
    //             if(data.status === 0) {
    //                 modal.style.display = 'none';
    //                 fetchData('query');
    //             }else if (data.status === -1){
    //                 modal.style.display = 'none';
    //             }
    //         } catch(err) {
    //             console.error('更新失败:', err);
    //         }
    //     };
    //     form.addEventListener('submit', currentEditHandler);
    //     modal.style.display = 'flex';
    // }
    // 新增修改功能逻辑
    async function updateRole(item) {
        const modal = document.getElementById('modal-mask-update');
        try {
            // 获取最新数据
            const res = await fetch(`http://localhost:8080/sys/waterway/detail/${item.id}`);
            const response = await res.json();

            if (response.status === 0) {
                const data = response.data;

                // 填充表单数据
                document.getElementById('update-name').value = data.name || '';
                document.getElementById('update-shortName').value = data.shortName || '';
                document.getElementById('update-address').value = data.address || '';
                document.getElementById('update-phone').value = data.phone || '';
                document.getElementById('update-email').value = data.email || '';

                // 存储当前编辑ID
                modal.dataset.currentId = item.id;
                modal.style.display = 'flex';
            }
        } catch (err) {
            console.error('加载详情失败:', err);
            alert(`数据加载失败: ${err.message}`);
        }
    }

    // 修改表单提交处理
    document.getElementById('modal-form-update').addEventListener('submit', async (e) => {
        e.preventDefault();

        const modal = document.getElementById('modal-mask-update');
        const id = modal.dataset.currentId;

        const formData = {
            id: id,
            name: document.getElementById('update-name').value,
            shortName: document.getElementById('update-shortName').value,
            address: document.getElementById('update-address').value,
            phone: document.getElementById('update-phone').value,
            email: document.getElementById('update-email').value
        };

        try {
            const res = await fetch('http://localhost:8080/sys/waterway/update', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            const response = await res.json();
            if (response.status === 0) {
                alert('修改成功');
                modal.style.display = 'none';
                fetchData('query'); // 刷新表格
            } else {
                alert('修改失败：' + (response.message || '未知错误'));
            }
        } catch (err) {
            console.error('提交失败:', err);
            alert('提交失败：' + err.message);
        }
    });
    function getStatusText (status){
        let state ='';
        switch (status){
            case 1 : state='合作中'
                break;
            case 0 : state='终止合作'
                break;
            default :
                state='--'
                break;
        }
        return state;
    }
</script>
</body>
</html>